package com.freight.core.common.utils;

import com.freight.core.common.constant.PropertiesConstant;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import static cn.hutool.db.DbUtil.close;

/**
 * @author hytma
 */
@Slf4j
public class MysqlUtil {
    public static Connection getConnection() {
        Connection con = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = PropertiesConstant.MYSQL_URL;
            String user = PropertiesConstant.MYSQL_USERNAME;
            String password = PropertiesConstant.MYSQL_PASSWORD;
            //注意，这里替换成你自己的mysql 数据库路径和用户名、密码
            con = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            System.out.println("-----------mysql get connection has exception , msg = " + e.getMessage());
        }
        return con;
    }

    /**
     * insert方法
     *
     * @param conn
     * @param sql
     * @param parems
     * @return
     * @throws SQLException
     */
    public static int insert(Connection conn, String sql, Object[] parems) throws SQLException {
        PreparedStatement stmt = null;
        try {
            stmt = conn.prepareStatement(sql);
            //判断是否有信息增加
            if (null != parems && parems.length > 0) {
                for (int i = 0; i < parems.length; i++) {
                    //使用给定对象设置指定参数的值
                    stmt.setObject(i + 1, parems[i]);
                }
            }
            int count = stmt.executeUpdate();

            return count;
        } finally {
            close(stmt);
        }
    }


}

